
import React, { useState, useEffect } from'react';
import { useNavigate } from'react-router-dom';
import './index.less';
import '@fortawesome/fontawesome-free/css/all.min.css';

// 模拟数据
const recommendData = [
  { id: 1, title: '测试', author: 'yanbg6', comment: '0评论', time: '12小时内' },
  { id: 2, title: 'mqm', author: '15879513035', comment: '0评论', time: '4天内' },
  { id: 3, title: 'testtest0003', author: '19088888889', comment: '14评论', time: '15小时内' },
  { id: 4, title: 'testtest0004', author: 'yanboming6', comment: '1评论', time: '12小时内' },
  { id: 5, title: 'testtest0005', author: '15879513035', comment: '0评论', time: '4天内' },
  { id: 6, title: 'testtest0006', author: '19088888889', comment: '0评论', time: '35分钟内' },
  { id: 7, title: 'testtest0007', author: 'yanboming6', comment: '0评论', time: '12小时内' },
  { id: 8, title: 'testtest0008', author: '15879513035', comment: '14评论', time: '15小时内' },
  { id: 9, title: 'testtest0009', author: '19088888889', comment: '1评论', time: '12小时内' },
  { id: 10, title: 'testtest0010', author: 'yanboming6', comment: '0评论', time: '4天内' },
  { id: 11, title: 'testtest0011', author: '15879513035', comment: '0评论', time: '35分钟内' },
  { id: 12, title: 'testtest0012', author: '19088888889', comment: '0评论', time: '12小时内' },
  { id: 13, title: 'testtest0013', author: 'yanboming6', comment: '14评论', time: '15小时内' },
  { id: 14, title: 'testtest0014', author: '15879513035', comment: '1评论', time: '12小时内' },
  { id: 15, title: 'testtest0015', author: '19088888889', comment: '0评论', time: '4天内' },
  { id: 16, title: 'testtest0016', author: 'yanboming6', comment: '0评论', time: '35分钟内' },
  { id: 17, title: 'testtest0017', author: '15879513035', comment: '0评论', time: '12小时内' },
  { id: 18, title: 'testtest0018', author: '19088888889', comment: '14评论', time: '15小时内' },
  { id: 19, title: 'testtest0019', author: 'yanboming6', comment: '1评论', time: '12小时内' },
  { id: 20, title: 'testtest0020', author: '15879513035', comment: '0评论', time: '4天内' },
  { id: 21, title: 'testtest0021', author: '19088888889', comment: '0评论', time: '35分钟内' },
  { id: 22, title: 'testtest0022', author: 'yanboming6', comment: '0评论', time: '12小时内' },
  { id: 23, title: 'testtest0023', author: '15879513035', comment: '14评论', time: '15小时内' },
  { id: 24, title: 'testtest0024', author: '19088888889', comment: '1评论', time: '12小时内' },
  { id: 25, title: 'testtest0025', author: 'yanboming6', comment: '0评论', time: '4天内' },
  { id: 26, title: 'testtest0026', author: '15879513035', comment: '0评论', time: '35分钟内' },
  { id: 27, title: 'testtest0027', author: '19088888889', comment: '0评论', time: '12小时内' },
  { id: 28, title: 'testtest0028', author: 'yanboming6', comment: '14评论', time: '15小时内' },
  { id: 29, title: 'testtest0029', author: '15879513035', comment: '1评论', time: '12小时内' },
  { id: 30, title: 'testtest0030', author: '19088888889', comment: '0评论', time: '4天内' },
];

const htmlData = [
  { id: 3, title: '7777777777', author: '19088888889', comment: '14评论', time: '15小时内' },
  { id: 4, title: '9000000000', author: 'yanboming6', comment: '1评论', time: '12小时内' }
];

// 定义 Channel 类型
type Channel = {
  key: string;
  title: string;
};

const HomePage = () => {
  const navigate = useNavigate();
  const [activeTab, setActiveTab] = useState('recommend');
  const [activeIndex, setActiveIndex] = useState(0);
  const visibleCount = 5;
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [isEditing, setIsEditing] = useState(false);

  const tabs = [
    { key:'recommend', title: '推荐' },
    { key: 'html', title: 'html' },
    { key: 'css', title: 'css' },
    { key: 'database', title: '数据库' },
    { key: 'blockchain', title: '区块链' },
    { key: 'go', title: 'go' },
    { key: 'product', title: '产品' }
  ];

  const [myChannels, setMyChannels] = useState<Channel[]>([
    { key:'recommend', title: '推荐' },
    { key: 'html', title: 'html' },
    { key: 'c++', title: 'c++' },
    { key: 'database', title: '数据库' },
    { key: 'blockchain', title: '区块链' },
    { key: 'go', title: 'go' },
    { key: 'product', title: '产品' },
    { key: 'backend', title: '后端' },
    { key: 'linux', title: 'linux' }
  ]);

  const [optionalChannels, setOptionalChannels] = useState<Channel[]>([
    { key: 'ai', title: '人工智能' },
    { key: 'php', title: 'php' },
    { key: 'javascript', title: 'javascript' },
    { key: 'architecture', title: '架构' },
    { key: 'frontend', title: '前端' },
    { key: 'python', title: 'python' },
    { key: 'java', title: 'java' },
    { key: 'algorithm', title: '算法' },
    { key: 'interview', title: '面试' },
    { key: 'tech-news', title: '科技动态' },
    { key: 'js', title: 'js' },
    { key: 'design', title: '设计' },
    { key: 'digital-product', title: '数码产品' },
    { key:'software-test', title: '软件测试' }
  ]);

  const [recommendList, setRecommendList] = useState(recommendData.slice(0, 10));
  const [htmlList, setHtmlList] = useState(htmlData.slice(0, 5));
  const [isLoading, setIsLoading] = useState(false);
  const [recommendPage, setRecommendPage] = useState(1);
  const [htmlPage, setHtmlPage] = useState(1);
  const [hasMoreRecommend, setHasMoreRecommend] = useState(recommendData.length > 5);
  const [hasMoreHtml, setHasMoreHtml] = useState(htmlData.length > 5);

  // 为 targetIndex 参数添加 number 类型注解
  const calculateStartIndex = (targetIndex: number) => {
    const middleIndex = Math.floor(visibleCount / 2);
    let startIndex = targetIndex - middleIndex;
    if (startIndex < 0) {
      startIndex = 0;
    }
    if (startIndex + visibleCount > tabs.length) {
      startIndex = tabs.length - visibleCount;
    }
    return startIndex;
  };

  // 为 channel 参数添加 Channel 类型注解
  const handleDeleteChannel = (channel: Channel) => {
    const filteredMyChannels = myChannels.filter(c => c.key!== channel.key);
    const updatedOptionalChannels = [...optionalChannels, { key: channel.key, title: channel.title }];
    setMyChannels(filteredMyChannels);
    setOptionalChannels(updatedOptionalChannels);
    alert('删除成功');
  };

  // 为 channel 参数添加 Channel 类型注解
  const handleAddChannel = (channel: Channel) => {
    const updatedMyChannels = [...myChannels, channel];
    const filteredOptionalChannels = optionalChannels.filter(c => c.key!== channel.key);
    setMyChannels(updatedMyChannels);
    setOptionalChannels(filteredOptionalChannels);
  };

  const handleScroll = () => {
    if (isLoading || (!hasMoreRecommend && activeTab ==='recommend') || (!hasMoreHtml && activeTab === 'html')) return;

    const scrollTop = window.pageYOffset;
    const windowHeight = window.innerHeight;
    const documentHeight = document.documentElement.scrollHeight;

    if (scrollTop + windowHeight >= documentHeight - 50) {
      setIsLoading(true);

      switch (activeTab) {
        case'recommend':
          const nextRecommendPage = recommendPage + 1;
          const start = (nextRecommendPage - 1) * 5;
          const end = nextRecommendPage * 5;
          const moreRecommend = recommendData.slice(start, end);
          if (moreRecommend.length > 0) {
            setRecommendList(prev => [...prev, ...moreRecommend]);
            setRecommendPage(nextRecommendPage);
            setHasMoreRecommend(end < recommendData.length);
          } else {
            setHasMoreRecommend(false);
          }
          break;
        case 'html':
          const nextHtmlPage = htmlPage + 1;
          const htmlStart = (nextHtmlPage - 1) * 5;
          const htmlEnd = nextHtmlPage * 5;
          const moreHtml = htmlData.slice(htmlStart, htmlEnd);
          if (moreHtml.length > 0) {
            setHtmlList(prev => [...prev, ...moreHtml]);
            setHtmlPage(nextHtmlPage);
            setHasMoreHtml(htmlEnd < htmlData.length);
          } else {
            setHasMoreHtml(false);
          }
          break;
        default:
          break;
      }

      setIsLoading(false);
    }
  };

  useEffect(() => {
    window.addEventListener('scroll', handleScroll);
    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, [activeTab]);

  const renderTabContent = () => {
    switch (activeTab) {
      case'recommend':
        return (
          <div className="tab-content">
            {recommendList.map(item => (
              <div key={item.id} className="list-item">
                <h3>{item.title}</h3>
                <p>{item.author} - {item.comment} - {item.time}</p>
              </div>
            ))}
            {isLoading && <div className="loading">加载中...</div>}
            {!hasMoreRecommend && <div className="no-more">没有更多数据</div>}
          </div>
        );
      case 'html':
        return (
          <div className="tab-content">
            {htmlList.map(item => (
              <div key={item.id} className="list-item">
                <h3>{item.title}</h3>
                <p>{item.author} - {item.comment} - {item.time}</p>
              </div>
            ))}
            {isLoading && <div className="loading">加载中...</div>}
            {!hasMoreHtml && <div className="no-more">没有更多数据</div>}
          </div>
        );
      default:
        return <div className="tab-content"></div>;
    }
  };

  return (
    <>
      <div className="tab-bar" style={{ position: 'fixed', top: 0, left: 0, width: '100%', overflow: 'hidden', zIndex: 100 }}>
        {(() => {
          const targetIndex = tabs.findIndex(t => t.key === activeTab);
          const startIndex = calculateStartIndex(targetIndex);
          const visibleTabs = tabs.slice(startIndex, startIndex + visibleCount);
          return visibleTabs.map((tab, index) => (
            <div
              key={tab.key}
              onClick={() => {
                setActiveTab(tab.key);
                setActiveIndex(calculateStartIndex(tabs.findIndex(t => t.key === tab.key)));
              }}
              className={`tab-item ${activeTab === tab.key? 'active' : ''}`}
            >
              {tab.title}
            </div>
          ));
        })()}
        <div className="icon-container" style={{ position: 'absolute', right: 0, top: 0, display: 'flex' }}>
          <i
            className="fas fa-search"
            style={{ margin: '4px' }}
            onClick={() => navigate('/search')}
          ></i>
          <i className="fas fa-ellipsis-v" style={{ margin: '4px' }} onClick={() => setDrawerVisible(true)}></i>
        </div>
      </div>
      {drawerVisible && (
        <div className={`drawer ${drawerVisible? 'visible' : ''}`}>
          <i
            className="fas fa-times"
            onClick={() => setDrawerVisible(false)}
            style={{ position: 'absolute', right: 10, top: 10, cursor: 'pointer' }}
          ></i>
          <div className="drawer-content">
            <div className="my-channels" style={{ display: 'flex', alignItems: 'center', marginBottom: '10px' }}>
              <span style={{ fontSize: '18px' }}>我的频道：</span>
              <div style={{ marginLeft: 'auto' }}>
                {isEditing? (
                  <button className="finish-btn" onClick={() => setIsEditing(false)}>完成</button>
                ) : (
                  <button className="edit-btn" onClick={() => setIsEditing(true)}>编辑</button>
                )}
              </div>
            </div>
            <div className="channel-group" style={{ display: 'flex', flexWrap: 'wrap', alignContent: 'flex-start' }}>
              {myChannels.map(tab => (
                <div key={tab.key} style={{ position: 'relative' }}>
                  <span
                    className={`channel-item ${activeTab === tab.key? 'active' : ''}`}
                    onClick={() => {
                      if (!isEditing) {
                        setActiveTab(tab.key);
                        setDrawerVisible(false);
                      }
                    }}
                    style={{ fontSize: '18px', padding: '5px 10px' }}
                  >
                    {tab.title}
                  </span>
                  {isEditing && (
                    <i
                      className="close-icon"
                      style={{ position: 'absolute', top: '-5px', right: '-5px', cursor: 'pointer', fontSize: '12px' }}
                      onClick={() => handleDeleteChannel(tab)}
                    >
                      ×
                    </i>
                  )}
                </div>
              ))}
            </div>
            <div className="optional-channels" style={{ marginTop: '20px' }}>
              <span style={{ fontSize: '18px' }}>可选频道：</span>
              <div className="channel-group" style={{ display: 'flex', flexWrap: 'wrap', alignContent: 'flex-start' }}>
                {optionalChannels.map(chan => (
                  <span
                    key={chan.key}
                    className="channel-item"
                    style={{ fontSize: '18px', padding: '5px 10px', marginBottom: '8px' }}
                    onClick={() => handleAddChannel(chan)}
                  >
                    + {chan.title}
                  </span>
                ))}
              </div>
            </div>
          </div>
        </div>
      )}
      {renderTabContent()}
    </>
  );
};

export default HomePage;    

